//
//  BSKSignupViewController.m
//  MicroMemory
//
//  Created by rimi on 16/7/8.
//  Copyright © 2016年 BlueSky. All rights reserved.
//

#import <LeanCloudSocial/AVOSCloudSNS.h>
#import <AVOSCloud/AVOSCloud.h>
#import <LeanCloudSocial/AVUser+SNS.h>
#import <KVNProgress/KVNProgress.h>

#import "BSKSignupViewController.h"
#import "UIView+SDAutoLayout.h"
#import "BSKUserCenterViewController.h"
#import "BSKStringCheck.h"
#import "BSKTheme.h"
#import "BSKconsts.h"
#import "BSKDBManager.h"
#import "UIViewController+BSKToast.h"
#import "IQKeyboardManager.h"

@interface BSKSignupViewController () <UITextFieldDelegate>
@property (strong, nonatomic) UIView *navView;
@property (strong, nonatomic) UIButton *backButton;
@property (strong, nonatomic) UILabel *titleLabel;

@property (strong, nonatomic) UIScrollView *contentScrollView;
@property (strong, nonatomic) UIView *nickNameView;
@property (strong, nonatomic) UIImageView *nickNameImageView;
@property (strong, nonatomic) UITextField *nickNameTextField;
@property (strong, nonatomic) UIView *emailView;
@property (strong, nonatomic) UIImageView *emailImageView;
@property (strong, nonatomic) UITextField *emailTextField;
@property (strong, nonatomic) UIView *passwordView;
@property (strong, nonatomic) UIImageView *passwordImageView;
@property (strong, nonatomic) UITextField *passwordTextField;
@property (strong, nonatomic) UIView *surePasswordView;
@property (strong, nonatomic) UIImageView *surePasswordImageView;
@property (strong, nonatomic) UITextField *surePasswordTextField;
@property (strong, nonatomic) UIButton *signupButton;

@property (assign, nonatomic) NSInteger flag;
@end

@implementation BSKSignupViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [IQKeyboardManager sharedManager].shouldResignOnTouchOutside = YES;
    self.view.backgroundColor = [UIColor colorWithRed:0.9525 green:0.9525 blue:0.9525 alpha:1.0];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self initializeUserInterface];
}
- (void)viewDidAppear:(BOOL)animated {
    _flag = 0;
    [super viewDidAppear:animated];
    [self.nickNameTextField becomeFirstResponder];
}
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    if (_flag == 0) {
        CGFloat contentHeight = 50 + 50 + 10 + 50 + 10 + 50 + 10 + 50 + 30 + 50 + 30;
        if (self.contentScrollView.height_sd <= contentHeight) {
            self.contentScrollView.contentSize = CGSizeMake(self.view.width, contentHeight);
        } else {
            self.contentScrollView.contentSize = self.contentScrollView.size_sd;
        }
        _flag = 1;
    }
}
- (void)initializeUserInterface {
    UIBlurEffect * efect = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    UIVisualEffectView *coverView = [[UIVisualEffectView alloc]initWithEffect:efect];
    UIImageView *imageView = [[UIImageView alloc] init];
    self.navView = [[UIView alloc] init];
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.titleLabel = [[UILabel alloc] init];
    self.contentScrollView = [[UIScrollView alloc] init];
    self.nickNameView = [[UIView alloc] init];
    self.nickNameImageView = [[UIImageView alloc] init];
    self.nickNameTextField = [[UITextField alloc] init];
    self.emailView = [[UIView alloc] init];
    self.emailImageView = [[UIImageView alloc] init];
    self.emailTextField = [[UITextField alloc] init];
    self.passwordView = [[UIView alloc] init];
    self.passwordImageView = [[UIImageView alloc] init];
    self.passwordTextField = [[UITextField alloc] init];
    self.surePasswordView = [[UIView alloc] init];
    self.surePasswordImageView = [[UIImageView alloc] init];
    self.surePasswordTextField = [[UITextField alloc] init];
    self.signupButton = [[UIButton alloc] init];
    
    [self.view addSubview:imageView];
    [self.view addSubview:coverView];
    [self.view addSubview:self.navView];
    [self.navView addSubview:self.backButton];
    [self.navView addSubview:self.titleLabel];
    [self.view addSubview:self.contentScrollView];
    [self.contentScrollView addSubview:self.nickNameView];
    [self.nickNameView addSubview:self.nickNameImageView];
    [self.nickNameView addSubview:self.nickNameTextField];
    [self.contentScrollView addSubview:self.emailView];
    [self.emailView addSubview:self.emailImageView];
    [self.emailView addSubview:self.emailTextField];
    [self.contentScrollView addSubview:self.passwordView];
    [self.passwordView addSubview:self.passwordImageView];
    [self.passwordView addSubview:self.passwordTextField];
    [self.contentScrollView addSubview:self.surePasswordView];
    [self.surePasswordView addSubview:self.surePasswordImageView];
    [self.surePasswordView addSubview:self.surePasswordTextField];
    [self.contentScrollView addSubview:self.signupButton];
    
    coverView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    
    imageView.sd_layout.topEqualToView(self.view)
    .leftEqualToView(self.view)
    .bottomEqualToView(self.view)
    .rightEqualToView(self.view);
    imageView.image = [BSKTheme curentTheme].themeImage;
    
    self.navView.sd_layout.topEqualToView(self.view)
    .widthRatioToView(self.view, 1)
    .heightIs(NavigationBarHeight + StatusBarHeight);
    //    self.navView.backgroundColor = [BSKTheme curentTheme].themeColor;
    
    self.backButton.sd_layout.topSpaceToView(self.navView, StatusBarHeight + 5)
    .leftSpaceToView(self.navView, 5)
    .widthIs(NavigationBarHeight - 10)
    .heightIs(NavigationBarHeight - 10);
    self.backButton.imageEdgeInsets = UIEdgeInsetsMake(3, 3, 3, 3);
    [self.backButton setImage:[UIImage imageNamed:@"back" ] forState:UIControlStateNormal];
    [self.backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    
    self.titleLabel.sd_layout.centerXIs(self.view.centerX)
    .centerYEqualToView(self.backButton);
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.font = [UIFont systemFontOfSize:20];
    self.titleLabel.textAlignment = NSTextAlignmentCenter;
    self.titleLabel.text = @"注册";
    [self.titleLabel sizeToFit];
    
    self.contentScrollView.sd_layout.topSpaceToView(self.navView, 0)
    .widthRatioToView(self.view, 1)
    .leftEqualToView(self.view)
    .bottomSpaceToView(self.view, 0);
    self.contentScrollView.bounces = NO;
    self.contentScrollView.showsVerticalScrollIndicator = NO;
    
    self.nickNameView.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.contentScrollView, 50)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(50);
    self.nickNameView.layer.cornerRadius = 10;
    self.nickNameView.layer.masksToBounds = YES;
    //    self.nickNameView.layer.borderWidth = 1;
    //    self.nickNameView.layer.borderColor = [UIColor whiteColor].CGColor;
    
    UIView *lineView1 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView1];
    lineView1.sd_layout.topSpaceToView(self.nickNameView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView1.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.nickNameImageView.sd_layout.topSpaceToView(self.nickNameView, 10)
    .leftSpaceToView(self.nickNameView, 10)
    .widthIs(30)
    .heightIs(30);
    self.nickNameImageView.image = [UIImage imageNamed:@"user"];
    
    self.nickNameTextField.sd_layout.topEqualToView(self.nickNameView)
    .leftSpaceToView(self.nickNameImageView, 10)
    .rightEqualToView(self.nickNameView)
    .heightIs(50);
    self.nickNameTextField.delegate = self;
    self.nickNameTextField.borderStyle = UITextBorderStyleNone;
    self.nickNameTextField.placeholder = @"请输入昵称";
    [self.nickNameTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.nickNameTextField.textColor = [UIColor whiteColor];
    self.nickNameTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.nickNameTextField.returnKeyType = UIReturnKeyNext;
    self.nickNameTextField.keyboardType = UIKeyboardTypeDefault;
    
    self.emailView.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.nickNameView, 10)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(50);
    self.emailView.layer.cornerRadius = 10;
    self.emailView.layer.masksToBounds = YES;
    
    UIView *lineView2 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView2];
    lineView2.sd_layout.topSpaceToView(self.emailView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView2.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.emailImageView.sd_layout.topSpaceToView(self.emailView, 10)
    .leftSpaceToView(self.emailView, 10)
    .widthIs(30)
    .heightIs(30);
    self.emailImageView.image = [UIImage imageNamed:@"email"];
    
    self.emailTextField.sd_layout.topEqualToView(self.emailView)
    .leftSpaceToView(self.emailImageView, 10)
    .rightEqualToView(self.emailView)
    .heightIs(50);
    self.emailTextField.delegate = self;
    self.emailTextField.borderStyle = UITextBorderStyleNone;
    self.emailTextField.placeholder = @"请输入注册邮箱";
    [self.emailTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.emailTextField.textColor = [UIColor whiteColor];
    self.emailTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.emailTextField.returnKeyType = UIReturnKeyNext;
    self.emailTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.emailTextField.keyboardType = UIKeyboardTypeEmailAddress;
    
    self.passwordView.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.emailView, 10)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(50);
    self.passwordView.layer.cornerRadius = 10;
    self.passwordView.layer.masksToBounds = YES;
    
    UIView *lineView3 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView3];
    lineView3.sd_layout.topSpaceToView(self.passwordView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView3.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.passwordImageView.sd_layout.topSpaceToView(self.passwordView, 10)
    .leftSpaceToView(self.passwordView, 10)
    .widthIs(30)
    .heightIs(30);
    self.passwordImageView.image = [UIImage imageNamed:@"key"];
    
    self.passwordTextField.sd_layout.topEqualToView(self.passwordView)
    .leftSpaceToView(self.passwordImageView, 10)
    .rightEqualToView(self.passwordView)
    .heightIs(50);
    self.passwordTextField.delegate = self;
    self.passwordTextField.borderStyle = UITextBorderStyleNone;
    self.passwordTextField.placeholder = @"请输入6~16位密码";
    [self.passwordTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.passwordTextField.textColor = [UIColor whiteColor];
    self.passwordTextField.secureTextEntry = YES;
    self.passwordTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.passwordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.passwordTextField.returnKeyType = UIReturnKeyNext;
    
    self.surePasswordView.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.passwordView, 10)
    .leftSpaceToView(self.contentScrollView, 30)
    .rightSpaceToView(self.contentScrollView, 30)
    .heightIs(50);
    self.surePasswordView.layer.cornerRadius = 10;
    self.surePasswordView.layer.masksToBounds = YES;
    
    UIView *lineView4 = [[UIView alloc] init];
    [self.contentScrollView addSubview:lineView4];
    lineView4.sd_layout.topSpaceToView(self.surePasswordView, 0)
    .leftSpaceToView(self.contentScrollView, 40)
    .rightSpaceToView(self.contentScrollView, 40)
    .heightIs(1);
    lineView4.backgroundColor = [UIColor colorWithRed:0.8708 green:0.8708 blue:0.8708 alpha:1.0];
    
    self.surePasswordImageView.sd_layout.topSpaceToView(self.surePasswordView, 10)
    .leftSpaceToView(self.surePasswordView, 10)
    .widthIs(30)
    .heightIs(30);
    self.surePasswordImageView.image = [UIImage imageNamed:@"key"];
    
    self.surePasswordTextField.sd_layout.topEqualToView(self.surePasswordView)
    .leftSpaceToView(self.surePasswordImageView, 10)
    .rightEqualToView(self.surePasswordView)
    .heightIs(50);
    self.surePasswordTextField.delegate = self;
    self.surePasswordTextField.borderStyle = UITextBorderStyleNone;
    self.surePasswordTextField.placeholder = @"请再次输入密码";
    [self.surePasswordTextField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    self.surePasswordTextField.textColor = [UIColor whiteColor];
    self.surePasswordTextField.secureTextEntry = YES;
    self.surePasswordTextField.spellCheckingType = UITextSpellCheckingTypeNo;
    self.surePasswordTextField.clearButtonMode = UITextFieldViewModeWhileEditing;
    self.surePasswordTextField.returnKeyType = UIReturnKeyDone;
    
    self.signupButton.sd_layout.centerXIs(self.view.centerX)
    .topSpaceToView(self.surePasswordView, 30)
    .widthRatioToView(self.surePasswordView, 1)
    .heightIs(50);
    self.signupButton.backgroundColor = [BSKTheme curentTheme].themeColor;
    [self.signupButton setTitle:@"注册" forState:UIControlStateNormal];
    [self.signupButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.signupButton addTarget:self action:@selector(signupButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    self.signupButton.layer.cornerRadius = 5;
    self.signupButton.layer.masksToBounds = YES;
}
#pragma mark - 自定义方法
- (void)backButtonAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)signupButtonAction:(UIButton *)sender {
    [self.view endEditing:YES];
    sender.enabled = NO;
    if (![self textFieldCheck:_nickNameTextField]) {
        sender.enabled = YES;
    } else if (![self textFieldCheck:_emailTextField]) {
        sender.enabled = YES;
    } else if (![self textFieldCheck:_passwordTextField]) {
        sender.enabled = YES;
    } else if (![self textFieldCheck:_surePasswordTextField]) {
        sender.enabled = YES;
    } else {
        __weak typeof(self) weakSelf = self;
        [KVNProgress show];
        AVUser *user = [AVUser user];// 新建 AVUser 对象实例
        user.username = _emailTextField.text;// 设置用户名
        user.password = _passwordTextField.text;// 设置密码
        user.email = _emailTextField.text;// 设置邮箱
        [user signUpInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [weakSelf updateLocalSQL];
                [[AVUser currentUser] setObject:_nickNameTextField.text forKey:@"nickName"];
                [[AVUser currentUser] saveInBackground];
                [[NSNotificationCenter defaultCenter]postNotificationName:BSKuserStatusChangeNotification object:nil];
                [KVNProgress dismiss];
                [weakSelf.navigationController MakeToast:@"注册成功" WithTime:1.5];
                BSKUserCenterViewController * userCenter = [[BSKUserCenterViewController alloc]init];
                [weakSelf.navigationController pushViewController:userCenter animated:YES];
                // 注册成功
            } else {
                [KVNProgress dismiss];
                // 失败的原因可能有多种，常见的是用户名已经存在。
                switch (error.code) {
                    case 203:
                        [weakSelf presentAlertWithMessage:@"该邮箱已被注册！"];
                        break;
                        
                    default:
                        [weakSelf presentAlertWithMessage:@"注册失败，请检查网络后重试！"];
                        break;
                }
                sender.enabled = YES;
            }
        }];
    }
}
- (void)updateLocalSQL {
    BSKDBManager * manager = [[BSKDBManager alloc] init];
    [manager openDataBase:@"notedatabase.db"];
    NSString *userId = [AVUser currentUser].objectId;
    [manager updateDataToTable:@"type" Columnns:@[@[@"userID", userId]] condition:@"userID = 'null'"];
    [manager updateDataToTable:@"note" Columnns:@[@[@"userID", userId]] condition:@"userID = 'null'"];
    [manager.fmDatabase close];
}
- (void)presentAlertWithMessage:(NSString *)message {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"温馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
    [alert addAction:sureAction];
    [self presentViewController:alert animated:YES completion:nil];
}
- (void)appearAnimation {
    [UIView animateWithDuration:1 animations:^{
        self.contentScrollView.sd_layout.topSpaceToView(self.navView, 0);
    }];
}
#pragma mark - UITextFieldDelegate
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    
    if (textField == self.passwordTextField || textField == self.surePasswordTextField) {
        if (range.location > 15) {
            return NO;
        }
    }
    return YES;
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField endEditing:YES];
    if ([self textFieldCheck:textField]) {
        if (textField == self.nickNameTextField) {
            [self.emailTextField becomeFirstResponder];
        }
        if (textField == self.emailTextField) {
            [self.passwordTextField becomeFirstResponder];
        }
        if (textField == self.passwordTextField) {
            [self.surePasswordTextField becomeFirstResponder];
        }
        if (textField == self.surePasswordTextField) {
            [self signupButtonAction:nil];
        }
    }
    return YES;
}
- (BOOL)textFieldCheck:(UITextField *)textField {
    if (textField == self.nickNameTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"昵称不能为空！" WithTime:1.5];
            return NO;
        } else if (![BSKStringCheck validateNickname:textField.text]) {
            [self MakeToast:@"昵称过长" WithTime:1.5];
            return NO;
        }
    }
    if (textField == self.emailTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"邮箱不能为空！" WithTime:1.5];
            return NO;
        } else if (![BSKStringCheck validateEmail:textField.text]) {
            [self MakeToast:@"邮箱格式不正确！" WithTime:1.5];
            return NO;
        }
        
    }
    if (textField == self.passwordTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"密码不能为空！" WithTime:1.5];
            return NO;
        }  else if (![BSKStringCheck validatePassword:textField.text]) {
            [self MakeToast:@"请输入6~16位由拼音、字母、下划线组成的密码！" WithTime:1.5];
            return NO;
        }
        
    }
    if (textField == self.surePasswordTextField) {
        if (textField.text.length == 0) {
            [self MakeToast:@"请确认密码！" WithTime:1.5];
            return NO;
        } else if (![textField.text isEqualToString:self.passwordTextField.text]) {
            [self MakeToast:@"前后密码不一致！" WithTime:1.5];
            return NO;
        }
    }
    return YES;
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}
@end
